<template>
    <section>
        <div class="panel">
            <div class="panel-head">
                <strong><i class="el-icon-date"/><span class="title">商品查询</span></strong>
            </div>
            <div class="body-content">
                <el-form :inline="true" size='small'>
                    <el-form-item label="商品名称:">
                        <el-input v-model.trim="searchObj.name" clearable placeholder="" size='small' style="width:150px"/>
                    </el-form-item>
                    <el-form-item label="是否推荐 0 不推荐 1 推荐（输入0或1）:">
                        <el-input v-model.trim="searchObj.recommend" clearable placeholder="" size='small' style="width:150px"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit" size='small' icon="el-icon-search">查询</el-button>                        
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addeditDailog('add')" size='small'>新增</el-button>                 
                    </el-form-item>
                </el-form>
                <!--表格数据-->
                <el-table :data="tableData" v-loading="listLoading" element-loading-text="拼命加载中" border>
                    <el-table-column type='index' width='50' label="序号"/>
                    <el-table-column prop="title" label="商品名称"/>
                    <el-table-column label="商品类别" width='90'>
                        <template slot-scope="scope">
                            <div>{{ ((categoryList || []).filter( o => o.id === scope.row.goodType )[0] || {}).name || '' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="商品价格" width='100'/>
                    <el-table-column prop="attendTimes" label="参加人数" width='100'/>
                    <el-table-column prop="desc" label="商品描述"/>
                    <el-table-column label="是否推荐" width='90'>
                        <template slot-scope="scope">
                             <p v-if="scope.row.isRecommend =='0'">未推荐</p>
                             <p v-if="scope.row.isRecommend =='1'">推荐</p>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sort" label="排序" width='100'/>
                    <el-table-column label="商品图片">
                        <template slot-scope="scope">
                            <img :src="scope.row.goodImg" alt="logo" style="width: 50px;height: 50px;margin: 0 auto;"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="商品价格" width='100'/>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" @click="addeditDailog('edit',scope.row)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="deleteData(scope.$index,scope.row.id)" style="margin-top: 10px; margin-left:0;">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="paginationMargin">
                    <el-pagination layout="prev, pager, next" background :current-page='currentPage' :page-count='pageCount' @current-change="handleCurrentChange"/>
                </div>
                <!-- 弹窗 -->
                <el-dialog :title="dialogTitle" :close-on-click-modal='false' :visible.sync="dialogFormVisible" width="50%" @close="closeDailog">
                    <el-form label-width="180px">
                        <el-form-item label="商品名称:">
                            <el-input v-model.trim="dailogFrom.title" placeholder="商品名称" size='small' style="width:200px;"/>
                        </el-form-item>
                        <el-form-item label="商品图片:">
                            <el-form :inline="true">
                                <el-form-item>
                                    <el-input v-model.trim="dailogFrom.goodImg" style="width:280px;" size="small"/>
                                </el-form-item>
                                <el-form-item>
                                    <el-upload class="upload-demo" with-credentials name="file" ref="upload" :action="uploadURL" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success='handleSuccess' :file-list="fileList" :limit="1" :before-upload="beforeAvatarUpload">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                    </el-upload>
                                </el-form-item>
                            </el-form>
                        </el-form-item>
                        <!-- <el-form-item>
                            只能上传jpg/jpeg/png文件，且不超过300KB
                        </el-form-item> -->
                        <el-form-item label="商品类型:">
                            <el-select v-model="dailogFrom.goodType" size='small' placeholder="商品类型" style="width: 200px">
                                <el-option v-for="(value,key) in categoryList" :key="key" :label="value.name" :value="value.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="是否推荐:">
                            <el-select v-model="dailogFrom.isRecommend" size='small' placeholder="是否推荐" style="width: 200px">
                                <el-option v-for="(value,key) in options" :key="key" :label="value.name" :value="value.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序字段:">
                            <el-input type='number' min="1" v-model.number="dailogFrom.sort" placeholder="排序字段" style="width:120px;" size='small'/>
                        </el-form-item>
                        <el-form-item label="商品价格:">
                            <el-input type='number' min="1" v-model.number="dailogFrom.price" placeholder="商品价格" style="width:120px;" size='small'/>
                        </el-form-item>
                        <el-form-item label="参加人数:">
                            <el-input type='number' min="1" v-model.number="dailogFrom.attendTimes" placeholder="参加人数" style="width:120px;" size='small'/>
                        </el-form-item>
                        <el-form-item label="商品描述:">
                            <el-input type="textarea" :rows="2" v-model.trim="dailogFrom.desc" placeholder="商品描述" size='small' style="width: 300px"/>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="confirm">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </section>
</template>
<script>
import * as api from "../../api/api";
// import { PAGE_SIZE } from "@/config";

export default {
    data() {
        return {
            listLoading: false, //加载中
            searchObj: {
                name: "",
                recommend: "",
            }, //查询参数
            tableData: [], //查询列表
            currentPage: 1, // 当前页数
            pageCount: 1, // 总页数
            pageSize: 20,

            categoryList: [],

            dialogTitle: "", // 弹窗标题
            dialogType: "", // 弹窗类型

            dialogVisible: false,
            dialogFormVisible: false,
            formLabelWidth: "120px",
            dailogFrom: {
                goodImg: ''
            },

            uploadURL: `${api.uploadFileURL}`,
            fileList: [],
            options: [
                {
                    id: '0',
                    name: '不推荐'
                }, {
                    id: '1',
                    name: '推荐'
                }],
        };
    },
    watch: {
        dialogType() {
            if (this.dialogType === "add") {
                this.dialogTitle = "新增";
            } else {
                this.dialogTitle = "编辑";
            }
        }
    },
    methods: {
        // 点击查询
        onSubmit() {
            this.currentPage = 1; // 将页码置为第一页
            // 查询数据列表
            this.getDataList();
        },
        // 分页点击方法
        handleCurrentChange(val) {
            this.currentPage = val;
            // 查询数据列表
            this.getDataList();
        },
        // 查询数据列表
        getDataList() {
            this.listLoading = true;
            api.goodsList({
                ...this.searchObj,
                pageNum: this.currentPage,
                pageSize: this.pageSize,
            })
                .then(res => {
                    this.listLoading = false;
                    const list = res.data.content;
                    this.tableData = list;
                    this.pageCount = res.data.totalPages
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        // 新增/编辑 弹窗
        addeditDailog(type, rowData) {
            this.dialogType = type;
            if (type == 'edit') {
                this.dailogFrom = { ...rowData };
            }
            this.dialogFormVisible = true;
        },
        // 关闭弹窗 输入框数据清空
        closeDailog() {
            this.dailogFrom = {goodImg: ''};
            this.fileList = [];
        },
        // 商品类型
        getCategoryList(){
            api.categoryList()
                .then(res => {
                    console.log(res, 'res>>>>');
                    this.categoryList = res.data;
                })
        },
        //删除产品
        deleteData(index, id) {
            this.$confirm("此操作将永久删除, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    api.delGoods({ id }).then(res => {
                        // 改变页面显示
                        this.tableData.splice(index, 1);
                        // 重新请求列表
                        // this.getDataList();
                        // 提示成功
                        this.$message.success("删除成功!");
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },
        // 新增/编辑 确定
        confirm() {
            if (!this.dailogFrom.title) {
                this.$message.error("请输入商品名称!");
                return false;
            }
            if (!this.dailogFrom.goodImg) {
                this.$message.error("请上传商品图片!");
                return false;
            }
            if (!this.dailogFrom.goodType) {
                this.$message.error("请选择商品类型!");
                return false;
            }
            if (!this.dailogFrom.price) {
                this.$message.error("请输入商品价格!");
                return false;
            }else{
                this.dailogFrom.price = this.dailogFrom.price * 100;
            }
            if (!this.dailogFrom.attendTimes) {
                this.$message.error("请输入参加人数!");
                return false;
            }
            console.log(this.dailogFrom);
            api.addAndEditGoods(this.dailogFrom)
                .then(res => {
                    console.log(res, 'res>>>>');
                    this.$message.success(`${this.dialogType === "add" ? `添加` : `修改`}成功!`);
                    // 获取数据列表
                    this.getDataList();
                    this.dialogFormVisible = false;
                })
        },
        // 超出上传限制提示
        handleExceed() {
            this.$message.warning("当前限制只能上传 1 个文件");
        },
        // 文件移除事件
        handleRemove() {
            this.fileList = [];
            this.dailogFrom.goodImg = "";
        },
        // 上传成功
        handleSuccess(res) {
            console.log(res);
            if (res.code == 200) {
                this.$message.success("上传成功！");
                this.dailogFrom.goodImg = res.data;
            } else {
                this.$message.error(res.message);
            }
        },
        // 文件大小 文件名判断
        beforeAvatarUpload(file) {
            const fileName = file.name;
            const index = fileName.lastIndexOf(".");
            const fileFormat = fileName.substring(index + 1, fileName.length);
            const isName =
                fileFormat === "png" ||
                fileFormat === "jpg" ||
                fileFormat === "jpeg";
            const isLt800KB = file.size / 1024 < 800;
            if (!isName) {
                this.$message.error("上传文件只能是 png/jpg/jpeg 格式!");
                this.fileList = [];
            }
            if (!isLt800KB) {
                this.$message.error("上传文件大小不能超过 800KB!");
                this.fileList = [];
            }
            return isName && isLt800KB;
        },
        
    },
    mounted() {
        // 查询数据列表
        this.getDataList();
        // 获取商品类型列表
        this.getCategoryList();
    }
};
</script>

<style>
</style>
